<?php
namespace app\admin\controller;
use app\common\controller\AdminController;
use think\facade\View;

use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Env;
class Order extends AdminController {
    //客户列表
    public function index(){
        if($this->request->isPost()){
            $key=input('post.key');
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_client_order')
                ->fieldRaw("o.*,a.username,a.realname")
                ->alias('o')->join('admin a','o.pr_user=a.username','left')
                ->order('o.create_time desc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }

        //查询所有管理员（去除admin）
        $adminResult = Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username,realname')->select();
        View::assign('adminResult',$adminResult);
        $this->app->view->engine()->layout(false);
        return View::fetch();
    }

    //（我的订单）列表
    public function personindex(){

        if($this->request->isPost()){
            $key=input('post.key');
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_client_order')
                ->where(['o.pr_user'=> $this->admin['username']])
                ->fieldRaw("o.*,a.username,a.realname")
                ->alias('o')->join('admin a','o.pr_user=a.username','left')
                ->order('o.create_time desc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }
        $this->app->view->engine()->layout(false);
        return View::fetch();
    }


 
    //新建订单号
    public function add(){
        if($this->request->isPost()){
            $data=$this->request->post();
            if(empty($data['pr_user'])){
                $data['pr_user'] = $this->admin['username'];
            }
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['status'] = '待审核';

            // $userExist = \think\facade\Db::name('crm_customer')->where('phone', $data['phone'])->find();
            // if ($userExist){
            //     $msg = ['code' => -200,'msg'=>'抱歉，重复号码不可添加！','data'=>[]];
            //     return json($msg);
            // }

            $crmClientOrderModel=new \app\admin\model\CrmClientOrder();
            $id=$crmClientOrderModel->allowField($crmClientOrderModel->getTableFields())->insertGetId($data);

            if ($id){
                Db::table('ymwl_todo')->insert([
                    'title'=>'订单审核',
                    'mess'=>$this->admin['realname'].'添加订单'.$data['orderno'],
//                    'url'=>myurl('admin/order/editAudit',['id'=>$id]),
                    'url'=>'order/editAudit.html?id='.$id,
                    'createtime'=>time(),
                    'result'=>'待审核',
                    'admin_id'=>$this->admin['admin_id'],
                    'show_auth_group_id'=>actiongroup('Order/editAudit'),
                ]);
                $msg = ['code' => 0,'msg'=>'提交订单成功！','data'=>[]];

            }else{
                $msg = ['code' => -200,'msg'=>'提交失败！','data'=>[]];

            }
            return json($msg);
        }

        $userlist = \think\facade\Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('userlist',$userlist);
        // $userlist = Db::name('admin')->select();
        // var_dump($userlist);
        View::assign('username',$this->admin['username']);
        $this->app->view->engine()->layout(false);
        return View::fetch('order/add');
    }

    public function myedit(){
        $id=$this->request->param('id',0,'intval');
        if(!$id){
            $msg = ['code' => -200,'msg'=>'请求参数有误！','data'=>[]];
            return json($msg);
        }
        $result = Db::table('crm_client_order') ->where(['id' => $id])->where('pr_user','=',$this->admin['username'])->find();
        if(empty($result)){
            $msg = ['code' => -200,'msg'=>'订单不存在！','data'=>[]];
            return json($msg);
        }
        if($result['status']!=='审核不通过'){
            $msg = ['code' => -200,'msg'=>'订单'.$result['status'].'，无法编辑！','data'=>[]];
            return json($msg);
        }

        if($this->request->isPost()){

            $data=$this->request->post();
            $data['updatetime'] = time();
            $data['status'] = '待审核';
            unset($data['id']);

            $crmClientOrderModel=new \app\admin\model\CrmClientOrder();
            $crmClientOrderModel->update($data,['id'=>$id],$crmClientOrderModel->getTableFields());;

            Db::table('ymwl_todo')->insert([
                'title'=>'订单审核',
                'mess'=>$this->admin['username'].'编辑订单'.$data['orderno'],
//                'url'=>myurl('admin/order/editAudit',['id'=>$id]),
                'url'=>'order/editAudit.html?id='.$id,
                'createtime'=>time(),
                'result'=>'待审核',
                'admin_id'=>$this->admin['admin_id'],
                'show_auth_group_id'=>actiongroup('Order/editAudit'),
            ]);
            $msg = ['code' => 0,'msg'=>'提交订单成功！','data'=>[]];
            return json($msg);
        }

        $userlist = \think\facade\Db::name('admin')->where('group_id','<>', 1)->field('admin_id,username')->select();
        View::assign('result',$result);
        View::assign('userlist',$userlist);
        // $userlist = Db::name('admin')->select();
        // var_dump($userlist);
        View::assign('username',$this->admin['username']);
        $this->app->view->engine()->layout(false);
        return View::fetch('edit');
    }
    public function changeyewu(){
        if($this->request->isAjax()){
            $data  = $this->request->post();
            $custphone = $data['cphone'];
            $where=[];
            $where[] = ['phone','=',$custphone];
            $custinfo = Db::name('crm_customer')->field('`name`,`pr_user`')->where($where)->find();
            if ($custinfo) {
//                if ($custinfo['issuccess'] == 1) {
//                    $res['code'] = 0;
//                    $res['msg'] = "该客户已经成交了，请检查客户手机信息";
//                }else{
                    $res['code'] = 1;
                    $res['custname'] = $custinfo['name'];
                    $res['pr_user'] = $custinfo['pr_user'];
                    $res['msg'] = "客户名称:".$custinfo['name'].",所属业务员:".$custinfo['pr_user'];
//                }
            }else{
                $res['code'] = 0;
                $res['msg'] = "该客户信息没用找到";
            }

            $this->success($res);
        }
    }
    //删除订单
    public function del(){
        $id = Request::param('id');
//        判断是不是管理员组做删除

            // 对应的客户修改状态
            $orderinfo = Db::table('crm_client_order')->field('cphone')->where('id',$id)->find();
            $phone = $orderinfo['cphone'];
            $updatearr = [];
            $updatearr['issuccess'] = -1;
            Db::table('crm_customer')->where('phone',$phone)->update($updatearr);
            $result = Db::table('crm_client_order')->where('id',$id)->delete();
            if ($result){
                $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
                return json($msg);
            }

    }

    //我的订单删除
    public function mydel(){
        $id = Request::param('id');
         // 对应的客户修改状态
            $orderinfo = Db::table('crm_client_order')->field('cphone')->where('id','=',$id)->where('pr_user','=',$this->admin['username'])->find();
            if(empty($orderinfo)){
                $msg = ['code' => -200,'msg'=>'您要删除的订单不存在，或不属于您的订单！','data'=>[]];
                return json($msg);
            }
            $phone = $orderinfo['cphone'];
        $updatearr = [];
        $updatearr['issuccess'] = -1;
            Db::table('crm_customer')->where('phone',$phone)->update($updatearr);
        $result = Db::table('crm_client_order')->where('id',$id)->delete();
        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }

    }
//    订单审核
    public function shenhe(){
//        status 1 审核通过  -1审核不通过
        $id = Request::param('id',0);
        $status= Request::param('status',-1);
        $orderinfo = Db::table('crm_client_order')->where('id',$id)->find();
        $custphone = $orderinfo['cphone'];
        $custinfo = Db::table('crm_customer')->where('phone',$custphone)->find();
        if (trim($orderinfo['status']) != '待审核' && trim($orderinfo['status'])!=1 ) {
            $msg = ['code' => -200,'msg'=>'该订单已审核','data'=>[]];
            return json($msg);
        }
        if($status>0){
            $updatearr = [];
            $updatearr['issuccess'] = 1;
            Db::table('crm_customer')->where('id',$custinfo['id'])->update($updatearr);
            $result = Db::table('crm_client_order')->where('id',$id)->update(['status'=>'审核通过']);
        }else{
            $result = Db::table('crm_client_order')->where('id',$id)->update(['status'=>'审核不通过']);
        }
        if ($result){
            $msg = ['code' => 0,'msg'=>'审核成功','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'审核已成功','data'=>[]];
            return json($msg);
        }
    }
  
    //客户搜索
    public function clientSearch(){
        $page =input('page',1,'intval');
        $limit =input('limit',config('app.pageSize'),'intval');
        $keyword = Request::param('keyword',[],'trim');

        $mapAtTime = []; //添加时间
        $mapKhName = [];//客户名称
        $mapXsSource = [];//线索/客户来源
        $mapPrUser = [];//业务员/负责人
        if (isset($keyword['create_time']) && $keyword['create_time']!= ''){
            $at = $keyword['create_time'];//日期
            $end_at =date('Y-m-d',strtotime("$at+1day"));
            $mapAtTime = [['o.create_time','between time',[strtotime($at),strtotime($end_at)]]];
        }
        if ($keyword['cname'] != ''){
            $mapKhName = [['o.cname','like','%'.$keyword['cname'].'%']];
        }
        if ($keyword['phone'] != ''){
            $mapKhName = [['o.cphone','like','%'.$keyword['phone'].'%']];
        }

        if ($keyword['status']!= ''){

            $mapXsSource =  ['o.status' => $keyword['status']];
        }

        if ($keyword['pr_user'] != ''){
            $mapPrUser = [['o.pr_user','like','%'.$keyword['pr_user'].'%']];
        }
        $crmClientOrder=Db::table('crm_client_order')
            ->where($mapKhName)
            ->where($mapXsSource)
            ->where($mapPrUser)
            ->where($mapAtTime);
        if(!empty($keyword['timebucket'])){
            $crmClientOrder=$crmClientOrder->whereTime('create_time',$keyword['timebucket']);
        }
        $list  = $crmClientOrder
            ->fieldRaw("o.*,a.username,a.realname")
            ->alias('o')->join('admin a','o.pr_user=a.username','left')
            ->order('o.create_time desc')
            ->paginate(array('list_rows'=>$limit,'page'=>$page))
            ->toArray();
        return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);

    }
    //（我的客户）搜索
    public function personClientSearch(){
       $page =input('page',1,'intval');
        $limit =input('limit',config('app.pageSize'),'intval');
        $keyword = Request::param('keyword');

        $mapAtTime = []; //添加时间
        $mapKhName = [];//客户名称
        $mapXsSource = [];//线索/客户来源
        $mapPrUser = [];//业务员/负责人
        if (isset($keyword['create_time']) && $keyword['create_time']!= ''){
            $at = $keyword['create_time'];//日期
            $end_at =date('Y-m-d',strtotime("$at+1day"));
            $mapAtTime = [['o.create_time','between time',[strtotime($at),strtotime($end_at)]]];
        }
        if ($keyword['cname'] != ''){
            $mapKhName = [['o.cname','like','%'.$keyword['cname'].'%']];
        }
        if ($keyword['phone'] != ''){
            $mapKhName = [['o.cphone','like','%'.$keyword['phone'].'%']];
        }

        if ($keyword['status']!= ''){

            $mapXsSource =  ['o.status' => $keyword['status']];
        }

        $mapPrUser['pr_user'] =  $this->admin['username'];
        $crmClientOrder=Db::table('crm_client_order')
            ->where($mapKhName)
            ->where($mapXsSource)
            ->where($mapPrUser)
            ->where($mapAtTime);
        if(!empty($keyword['timebucket'])){
            $crmClientOrder=$crmClientOrder->whereTime('o.create_time',$keyword['timebucket']);
        }
        $list  = $crmClientOrder
            ->fieldRaw("o.*,a.username,a.realname")
            ->alias('o')->join('admin a','o.pr_user=a.username','left')
            ->order('o.create_time desc')
            ->paginate(array('list_rows'=>$limit,'page'=>$page))
            ->toArray();
        //var_dump($list);
        return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);


    }

//    订单审核删除
    public function delAudit(){
        //        status 1 审核通过  -1审核不通过
        $id = Request::param('id',0,'intval');
        if(!$id){
            return json(['code' => -200,'msg'=>'参数有误','data'=>[]]);
        }
        if($this->request->isAjax()){
            $status= Request::param('status',-1);
            $tudo_id= $this->request->post('tudo_id',0);
            if(!$tudo_id){
                return json(['code' => -200,'msg'=>'参数有误','data'=>[]]);
            }
            $result_mess= $this->request->post('result_mess','','trim');
            $todoDate=[];
            if($status>0){
//            允许删除
                $orderinfo = Db::table('crm_client_order')->field('cphone')->where('id',$id)->find();
                $phone = $orderinfo['cphone'];
                $updatearr = [];
                $updatearr['issuccess'] = -1;
                Db::table('crm_customer')->where('phone',$phone)->update($updatearr);
                $result = Db::table('crm_client_order')->where('id',$id)->delete();
                if ($result){
                    $todoDate=['result'=>'同意删除','result_mess'=>$result_mess,'is_finish'=>1];
                    $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
                }else{
                    $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
                }
            }else{
                $todoDate=['result'=>'拒绝删除','result_mess'=>$result_mess,'is_finish'=>1];
                Db::table('crm_client_order')->where('id',$id)->update(['isdel'=>-1]);
                $msg = ['code' => 0,'msg'=>'拒绝删除成功！','data'=>[]];
            }
            if($todoDate){
                $todoDate['audittime']=time();
                $todoDate['reviewer']=$this->admin['username'];
                Db::table('ymwl_todo')->where('id','=',$tudo_id)->update($todoDate);
            }
            return json($msg);
        }else{
            $result = Db::table('crm_client_order') ->where(['id' => $id])->find();
            View::assign('result',$result);
            $this->app->view->engine()->layout(false);
            return View::fetch();
        }


    }

    //    订单审核是否通过
    public function editAudit(){
        //        status 1 审核通过  -1审核不通过
        $id = Request::param('id',0,'intval');
        if(!$id){
            return json(['code' => -200,'msg'=>'参数有误','data'=>[]]);
        }
        if($this->request->isAjax()){
            $status= Request::param('status',-1);
            $tudo_id= $this->request->post('tudo_id',0);
            if(!$tudo_id){
                return json(['code' => -200,'msg'=>'参数有误','data'=>[]]);
            }
            $result_mess= $this->request->post('result_mess','','trim');
            $todoDate=[];

            $orderinfo = Db::table('crm_client_order')->where('id',$id)->find();
            if (trim($orderinfo['status']) != '待审核' ) {
                $msg = ['code' => -200,'msg'=>'该订单已审核','data'=>[]];
                return json($msg);
            }

            $custinfo = Db::table('crm_customer')->field('id')->where('phone',$orderinfo['cphone'])->find();
            if($status>0){
                //        status 1 审核通过  -1审核不通过
                $updatearr = [];
                $updatearr['issuccess'] = 1;
//                成功成功的转成客户
                $updatearr['status'] = 1;
                Db::table('crm_customer')->where('id',$custinfo['id'])->update($updatearr);
                $result=Db::table('crm_client_order')->where('id',$id)->update(['status'=>'审核通过']);
                $todoDate=['result'=>'审核通过','result_mess'=>$result_mess,'is_finish'=>1];
                $msg = ['code' => 0,'msg'=>'审核成功','data'=>[]];
            }else{
                $result = Db::table('crm_client_order')->where('id',$id)->update(['status'=>'审核不通过']);
                $todoDate=['result'=>'审核不通过','result_mess'=>$result_mess,'is_finish'=>1];
                $msg = ['code' => 0,'msg'=>'审核提交成功','data'=>[]];
            }
            if($todoDate && $result){
                $todoDate['audittime']=time();
                $todoDate['reviewer']=$this->admin['username'];
                Db::table('ymwl_todo')->where('id','=',$tudo_id)->update($todoDate);
            }else{
                $msg = ['code' => 0,'msg'=>'审核提交失败','data'=>[]];
            }
            return json($msg);
        }else{
            $result = Db::table('crm_client_order') ->where(['id' => $id])->find();
            View::assign('result',$result);
            $this->app->view->engine()->layout(false);
            return View::fetch();
        }


    }

    public function verify_orderno(){
        if($this->request->isPost()){
            $post=$this->request->post();
            if(empty($post['orderno'])){
                $msg = ['code' => -200,'msg'=>'订单号必须填写！','data'=>[]];
                return json($msg);
            }
            $where=[];
            if(!empty($post['id'])){
                $where[]=['id','<>',$post['id']];
            }
            $where[]=['orderno','=',$post['orderno']];
            $userExist = \think\facade\Db::name('crm_client_order')->field('orderno,pr_user')->where($where)->find();
            if ($userExist){
                if($userExist['pr_user']){
                    $msg='抱歉，当前订单号已存在，已经是'.$userExist['pr_user'].'的订单！';
                }else{
                    $msg='抱歉，当前订单号已存在！';
                }
                $msg = ['code' => -200,'msg'=>$msg,'data'=>[]];
            }else{
                $msg = ['code' => 0,'msg'=>'验证成功，允许添加'];
            }
            return json($msg);
        }
    }

    public function analytics(){
        if ($this->request->isAjax()) {

            $get = $this->request->get('', null, null);
            $filters = isset($get['filter']) && !empty($get['filter']) ? $get['filter'] : '{}';
            $filters = json_decode($filters, true);
            $month=empty($filters['month'])?date('Y-m'):$filters['month'];
            $uninx_time=strtotime( $month);
            $firstday = date('Y-m-01 00:00:00', $uninx_time);
            $lastday = date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day"));


            //月度排名（名）、月目标（元）、已成交（元）、完成率（%）、已成交（单）、提成点（%），
            //管理员添加业绩设置权限。
            $prefix=config('database.connections.mysql.prefix');
            $where='';
            if(!empty($filters['username'])){
                $where.=" AND `username` LIKE '%{$filters['username']}%'";
            }

            $userlist=Db::query("SELECT o.*,a.admin_id,a.username,a.realname,COALESCE(a.mubiao,0) mubiao,a.ticheng FROM {$prefix}admin a LEFT JOIN (SELECT SUM(`money`) AS money_month,COUNT( `id` ) AS number_month,SUM( `return_money` ) AS return_money_month,pr_user FROM {$prefix}`crm_client_order` WHERE `status` = '审核通过' AND create_time between '{$firstday}' AND '{$lastday}' GROUP BY `pr_user` ORDER BY money_month DESC) o ON a.username=o.pr_user WHERE a.admin_id<>1 AND a.is_open=1 {$where} ORDER BY o.money_month DESC");

            //处理重新计算提成点进行重置，根据回款进行计算
            if (!empty($userlist)) {
                $setticheng = Db::name('config')->where([['name','=','admin_setticheng_config'],['inc_type','=','setticheng']])->find();
                if (!empty($setticheng['value'])) {
                    $setticheng_config = json_decode($setticheng['value'],true);
                }
                foreach ($userlist as $k=>$user) {
                    $temp_ticheng = 0;
                    if (!empty($user['return_money_month']) && !empty($setticheng_config)) {
                        foreach ($setticheng_config as $ck => $config) {
                            if ($user['return_money_month'] >= $config['start_money']) {
                                //为空，则不限制，就近匹配
                                if (empty($config['end_money'])) {
                                    $temp_ticheng = $config['num'];
                                    break;
                                }

                                if ($user['return_money_month'] < $config['end_money']) {
                                    $temp_ticheng = $config['num'];
                                    break;
                                }
                            }
                        }
                    }
                    $userlist[$k]['ticheng'] = $temp_ticheng;
                    $userlist[$k]['username'] = $user['realname'];
                }
            }


            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => count($userlist),
                'data'  => $userlist,
                'cur_date'=>date('Y年m月',$uninx_time)
            ];
            return json($data);
        }
        return View::fetch();
    }

   


}